package com.yidian.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yidian.dao.CategoryBrandMapper;
import com.yidian.dao.CategoryMapper;
import com.yidian.dao.SkuMapper;
import com.yidian.dao.SpuMapper;
import com.yidian.entity.PageResult;
import com.yidian.pojo.goods.*;
import com.yidian.server.goods.SkuService;
import com.yidian.server.goods.SpuService;
import com.yidian.utils.IdWorkerBySnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author whb
 * @create 2021-05-25 11:07
 * @decription 标准产品单位Service实现类
 */
@Service(interfaceClass = SpuService.class)
public class SpuServiceImpl implements SpuService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuService skuService;

    /**
     * 返回全部记录
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(), spus.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(), spus.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     *
     * @param spu
     */
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }

    /**
     * 修改
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 删除
     * @param id
     */
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
        //根据spuId查询sku集合，获取skuId，根据skuId删除Redis缓存中的价格
        Map skuIdMap=new HashMap();
        skuIdMap.put("spuId",id);
        List<Sku> skuList = skuService.findList(skuIdMap);
        for (Sku sku:skuList){
            skuService.deletePriceFromRedis(sku.getId());
        }
    }

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private IdWorkerBySnowFlake idSnowFlake;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    /**
     * 新增/修改商品
     * @param goods 商品组合实体类
     */
    @Override
    @Transactional
    public void saveGoods(Goods goods) {
        //保存一个Spu信息
        Spu spu = goods.getSpu();
        if (spu.getId()==null){ //新增商品
            spu.setId(idSnowFlake.nextId()+"");
            spuMapper.insert(spu);
        }else { //修改Spu
            //删除商品原来Sku列表
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",spu.getId());
            skuMapper.deleteByExample(example);

            //修改Spu
            spuMapper.updateByPrimaryKeySelective(spu);
        }


        Date date = new Date();

        //获取分类信息
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());

        List<Sku> skuList = goods.getSkuList();
        for (Sku sku:skuList){
            if (sku.getId()==null){ //新增Sku
                sku.setId(idSnowFlake.nextId()+""); //生成Sku Id
                sku.setCreateTime(date); //创建日期
            }

            sku.setSpuId(spu.getId());

            //没有商品规格的处理
            if (sku.getSpec()==null || "".equals(sku.getSpec())){
                sku.setSpec("{}");
            }

            //sku名称 =spu名称+规格值列表
            String name = spu.getName();
            //sku.getSpec() {"颜色":"红","机身内存":"64G"}
            Map<String,String> specMap = JSONObject.parseObject(sku.getSpec(), Map.class);
            for (String value:specMap.values()){
                name+=" "+value;
            }
            sku.setName(name); //名称
            sku.setUpdateTime(date); //修改日期
            sku.setCategoryId(category.getId()); //分类id
            sku.setCategoryName(category.getName()); //分类名称
            sku.setCommentNum(0); //评论数
            sku.setSaleNum(0); //销售数量

            skuMapper.insertSelective(sku);

            //将新增或者修改过的价格重新保存到redis缓存
            skuService.savePriceToRedis(sku.getId(),sku.getPrice());
        }

        //建立分类和品牌的关联
        CategoryBrand categoryBrand=new CategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count==0){
            categoryBrandMapper.insertSelective(categoryBrand);
        }
    }

    /**
     * 根据ID查询商品
     * @param id
     * @return
     */
    @Override
    public Goods findGoodsById(String id) {
        //查询Spu
        Spu spu = spuMapper.selectByPrimaryKey(id);

        //查询Sku
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<Sku> skuList = skuMapper.selectByExample(example);

        //创建商品对象
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);
        return goods;
    }

    /**
     * 商品审核(如果已审核，商品上架)
     * @param id
     * @param status
     * @param message
     */
    @Override
    public void audit(String id, String status, String message) {
        //1.修改商品状态 审核状态和上架状态
        Spu spu = new Spu();
        spu.setId(id);
        spu.setStatus(status);
        if ("1".equals(status)){ //审核通过
            spu.setIsMarketable("1"); //商品上架
        }
        //修改审核状态
        spuMapper.updateByPrimaryKeySelective(spu);

        //2.记录商品审核记录

        //3.记录商品日志
    }

    /**
     * 商品下架
     * @param id
     */
    @Override
    public void pull(String id) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品上架
     * @param id
     */
    @Override
    public void put(String id) {
        //根据id查询Spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //判断商品是否已审核
        if (!"1".equals(spu.getStatus())){
            throw new RuntimeException("此商品未通过审核。");
        }
        spu.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spu);

        //记录商品日志
    }

    /**
     * 商品批量上架
     * @param ids
     * @return
     */
    @Override
    public int putMany(String[] ids) {
        Spu spu = new Spu();
        spu.setIsMarketable("1");
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids)); //要上架的商品所有id
        criteria.andEqualTo("status","1"); //已审核的商品
        criteria.andEqualTo("isDelete","0"); //非逻辑删除的商品

        //添加商品日志

        return spuMapper.updateByExampleSelective(spu, example);
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andLike("sn", "%" + searchMap.get("sn") + "%");
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andLike("isMarketable", "%" + searchMap.get("isMarketable") + "%");
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andLike("isEnableSpec", "%" + searchMap.get("isEnableSpec") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andLike("status", "%" + searchMap.get("status") + "%");
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }
}
